package io.itit.ecp.admin.provide.action.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import icu.mhb.mybatisplus.plugln.core.JoinLambdaWrapper;
import icu.mhb.mybatisplus.plugln.extend.Joins;
import io.itit.ecp.admin.provide.action.req.SceneCompanyQueryReq;
import io.itit.ecp.admin.provide.action.req.SceneCompanyReq;
import io.itit.ecp.admin.provide.action.resp.SceneCompanyResp;
import io.itit.ecp.admin.provide.renderer.SceneCompanyRenderer;
import io.itit.ecp.admin.server.entity.*;
import io.itit.ecp.admin.server.service.*;
import io.itit.grass.common.exception.GrassException;
import io.itit.grass.common.provide.action.req.BaseBatchIdReq;
import io.itit.grass.common.provide.action.req.BaseIdReq;
import io.itit.grass.common.provide.action.resp.ResultResp;
import io.itit.grass.common.provide.action.validation.*;
import io.itit.grass.common.server.utils.ConvertUtils;
import io.itit.grass.estelle.starter.core.ExcelXSSFUtil;
import io.itit.grass.estelle.starter.parse.ExcelParseManage;
import io.itit.grass.estelle.starter.util.JsonUtil;
import io.itit.grass.web.wall.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * @Author：Roy
 * @Description：公司控制类
 * @Date：Create by 2023-11-23 09:55:21
 */
@Api(tags = "公司管理")
@RestController
@RequestMapping("/ecp-admin/sceneCompany")
public class SceneCompanyController {

    @Resource
    private ISceneCompanyService sceneCompanyService;

    @Resource
    private ISceneRoomService sceneRoomService;

    @Resource
    private ISceneFloorService sceneFloorService;

    @Resource
    private ISceneEdificeService sceneEdificeService;

    @Resource
    private ISceneProjectService sceneProjectService;

    @ApiOperation("分页查询")
    @PostMapping("queryPage")
    public ResultResp<IPage<SceneCompanyResp>> queryPage(@RequestBody @Validated(IQueryPage.class) SceneCompanyQueryReq req) {
        Page<SceneCompanyResp> page = buildQW(req).joinPage(PageUtils.getPage(req, SceneCompanyResp.class), SceneCompanyResp.class);
        page.getRecords().forEach(company -> {
            // 查询空间列表
            List<SceneRoomEntity> rooms = sceneRoomService.lambdaQuery()
                    .select(SceneRoomEntity::getId, SceneRoomEntity::getSceneEdificeId,
                            SceneRoomEntity::getSceneFloorId, SceneRoomEntity::getRoomName, SceneRoomEntity::getRoomArea)
                    .eq(SceneRoomEntity::getSceneCompanyId, company.getId())
                    .list();
            if (!rooms.isEmpty()) {
                List<BigDecimal> areas = rooms.stream().map(SceneRoomEntity::getRoomArea).collect(Collectors.toList());
                BigDecimal sum = areas.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
                company.setCompanyArea(sum);
                List<String> roomIds = rooms.stream().map(SceneRoomEntity::getId).distinct().collect(Collectors.toList());
                List<String> roomNames = rooms.stream().map(SceneRoomEntity::getRoomName).collect(Collectors.toList());
                company.setSceneRoomIds(String.join(",", roomIds));
                company.setRoomNames(String.join("、", roomNames));
                // 查询楼栋名称
                List<String> edificeIds = rooms.stream().map(SceneRoomEntity::getSceneEdificeId).distinct().collect(Collectors.toList());
                List<SceneEdificeEntity> edifices = sceneEdificeService.lambdaQuery()
                        .select(SceneEdificeEntity::getEdificeName)
                        .in(SceneEdificeEntity::getId, edificeIds)
                        .orderByAsc(SceneEdificeEntity::getEdificeName)
                        .list();
                company.setSceneEdificeIds(String.join(",", edificeIds));
                company.setEdificeNames(String.join("、", edifices.stream().map(SceneEdificeEntity::getEdificeName).collect(Collectors.toList())));
                // 查询楼层名称
                List<String> floorIds = rooms.stream().map(SceneRoomEntity::getSceneFloorId).distinct().collect(Collectors.toList());
                List<SceneFloorEntity> floors = sceneFloorService.lambdaQuery()
                        .select(SceneFloorEntity::getFloorName)
                        .in(SceneFloorEntity::getId, floorIds)
                        .orderByAsc(SceneFloorEntity::getFloorName)
                        .list();
                company.setSceneFloorIds(String.join(",", floorIds));
                company.setFloorNames(String.join("、", floors.stream().map(SceneFloorEntity::getFloorName).collect(Collectors.toList())));
            }
        });
        return ResultResp.success(page);
    }


    @ApiOperation("树查询")
    @PostMapping("queryTree")
    public ResultResp<List<Map<String, Object>>> queryTree(@RequestBody SceneCompanyQueryReq req) {
        List<SceneProjectEntity> projectList = sceneProjectService.lambdaQuery().orderByDesc(SceneProjectEntity::getCreateTm).list();
        List<SceneEdificeEntity> edificeEntities = sceneEdificeService.lambdaQuery().orderByAsc(SceneEdificeEntity::getEdificeName).list();
        List<SceneFloorEntity> floorList = sceneFloorService.lambdaQuery().orderByAsc(SceneFloorEntity::getFloorNum).list();
        List<SceneRoomEntity> roomList = sceneRoomService.lambdaQuery().orderByAsc(SceneRoomEntity::getRoomName).list();
        Map<String, SceneCompanyResp> companyMap = buildQW(req).joinList(SceneCompanyResp.class).stream().collect(Collectors.toMap(SceneCompanyResp::getId, Function.identity()));
        List<Map<String, Object>> result = new ArrayList<>(projectList.size());
        Map<String, List<SceneEdificeEntity>> projectMap = edificeEntities.stream()
                .collect(Collectors.groupingBy(SceneEdificeEntity::getSceneProjectId));

        Map<String, List<SceneFloorEntity>> floorMap = floorList.stream()
                .collect(Collectors.groupingBy(SceneFloorEntity::getSceneEdificeId));
        Map<String, List<SceneRoomEntity>> floorCompanyMap = roomList.stream()
                .filter(item -> StringUtils.isNotEmpty(item.getSceneCompanyId()))
                .collect(Collectors.groupingBy(SceneRoomEntity::getSceneFloorId));
        for (SceneProjectEntity item : projectList) {
            Map<String, Object> m = new HashMap<>();
            m.put("id", item.getId());
            m.put("label", item.getProjectName());
            m.put("type", 1);
            m.put("children", projectMap.getOrDefault(item.getId(), Collections.emptyList()).stream().map(edifice -> {
                Map<String, Object> edificeMap = new HashMap<>();
                edificeMap.put("id", edifice.getId());
                edificeMap.put("label", edifice.getEdificeName());
                edificeMap.put("type", 2);
                edificeMap.put("children", floorMap.getOrDefault(edifice.getId(), Collections.emptyList()).stream().map(floor -> {
                    Map<String, Object> fMap = new HashMap<>();
                    fMap.put("id", floor.getId());
                    fMap.put("label", floor.getFloorName());
                    fMap.put("type", 3);
                    fMap.put("children", floorCompanyMap.getOrDefault(floor.getId(), Collections.emptyList())
                            .stream()
                            .filter(floorCompany -> companyMap.get(floorCompany.getSceneCompanyId()) != null)
                            .map(floorCompany -> {
                                Map<String, Object> rMap = new HashMap<>();
                                rMap.put("id", floorCompany.getSceneCompanyId());
                                rMap.put("label", companyMap.get(floorCompany.getSceneCompanyId()).getCompanyName());
                                rMap.put("type", 5);
                                return rMap;
                            }).collect(Collectors.toList()));
                    return fMap;
                }).collect(Collectors.toList()));
                return edificeMap;
            }).collect(Collectors.toList()));
            result.add(m);
        }
        return ResultResp.success(result);
    }

    @ApiOperation("详情")
    @PostMapping("detail")
    @RequiresPermissions("ecp-admin:sceneCompany:search")
    public ResultResp<SceneCompanyResp> detail(@RequestBody @Validated(IRequired.class) BaseIdReq req) {
        return ResultResp.success(ConvertUtils.copy(sceneCompanyService.getById(req.getId()), SceneCompanyResp.class));
    }

    /**
     * 组装查询条件
     *
     * @param req
     * @return
     */
    private static JoinLambdaWrapper<SceneCompanyEntity> buildQW(SceneCompanyQueryReq req) {
        return Joins.of(SceneCompanyEntity.class)
                .leftJoin(SceneRoomEntity.class, SceneRoomEntity::getSceneCompanyId, SceneCompanyEntity::getId)
                .select()
                .eq(StringUtils.isNotEmpty(req.getSceneProjectId()), SceneRoomEntity::getSceneProjectId, req.getSceneProjectId())
                .eq(StringUtils.isNotEmpty(req.getSceneEdificeId()), SceneRoomEntity::getSceneEdificeId, req.getSceneEdificeId())
                .eq(StringUtils.isNotEmpty(req.getSceneFloorId()), SceneRoomEntity::getSceneFloorId, req.getSceneFloorId())
                .end()
                .leftJoin(SceneProjectEntity.class, SceneProjectEntity::getId, SceneCompanyEntity::getSceneProjectId)
                .select(SceneProjectEntity::getProjectName)
                .end()
                .eq(StringUtils.isNotEmpty(req.getSceneProjectId()), SceneCompanyEntity::getSceneProjectId, req.getSceneProjectId())
                .like(StringUtils.isNotEmpty(req.getCompanyName()), SceneCompanyEntity::getCompanyName, req.getCompanyName())
                .eq(StringUtils.isNotEmpty(req.getDeptId()), SceneCompanyEntity::getDeptId, req.getDeptId())
                .in(CollectionUtils.isNotEmpty(req.getIds()), SceneCompanyEntity::getId, req.getIds())
                .last(StringUtils.isNotEmpty(req.getSortColumn()), PageUtils.lastOrderBy(req))
                .groupBy(SceneCompanyEntity::getId)
                .orderByDesc(SceneCompanyEntity::getCreateTm);
    }

    @ApiOperation("新增")
    @PostMapping("add")
    @RequiresPermissions("ecp-admin:sceneCompany:add")
    public ResultResp<Boolean> add(@RequestBody @Validated({IAdd.class}) SceneCompanyReq req) {
        checkDataExists(req);
        return ResultResp.success(sceneCompanyService.saveCompany(ConvertUtils.convertIgnoreId(req, SceneCompanyEntity.class), req.getRoomIds()));
    }

    @ApiOperation("编辑")
    @PostMapping("update")
    @RequiresPermissions("ecp-admin:sceneCompany:update")
    public ResultResp<Boolean> update(@RequestBody @Validated({IUpdate.class}) SceneCompanyReq req) {
        checkDataExists(req);
        return ResultResp.success(sceneCompanyService.updateCompany(ConvertUtils.copy(req, SceneCompanyEntity.class), req.getRoomIds(), req.getCancelRoomIds()));
    }

    private void checkDataExists(SceneCompanyReq req) {
        Long count = sceneCompanyService.lambdaQuery()
                .eq(SceneCompanyEntity::getCompanyName, req.getCompanyName())
                .ne(StringUtils.isNotEmpty(req.getId()), SceneCompanyEntity::getId, req.getId())
                .count();
        GrassException.throwEx(count > 0, "公司名称已存在！");
    }

    @ApiOperation("删除(根据Id删)")
    @PostMapping("deleteById")
    @RequiresPermissions("ecp-admin:sceneCompany:deleteById")
    public ResultResp<Boolean> deleteById(@RequestBody @Validated({IRequired.class}) BaseIdReq req) {
        return ResultResp.success(sceneCompanyService.removeById(req.getId()));
    }

    @ApiOperation("批量删除")
    @PostMapping("batchDelete")
    @RequiresPermissions("ecp-admin:sceneCompany:batchDelete")
    public ResultResp<Boolean> batchDelete(@RequestBody @Validated({IRequired.class}) BaseBatchIdReq req) {
        return ResultResp.success(sceneCompanyService.removeBatchByIds(req.getIds(), 1000));
    }

    @ApiOperation("导入")
    @PostMapping("upload")
    @RequiresPermissions("ecp-admin:sceneCompany:upload")
    public ResultResp<Integer> upload(@RequestParam("file") MultipartFile file, Boolean ignoreError) {
        return ResultResp.success(ExcelParseManage.i().process(SceneCompanyRenderer.ENTITY_NAME, file, ignoreError));
    }

    @ApiOperation("导出")
    @PostMapping("export")
    @RequiresPermissions("ecp-admin:sceneCompany:export")
    public void export(@RequestBody @Validated(IExport.class) SceneCompanyQueryReq req, HttpServletResponse response) {
        ExcelXSSFUtil.export("SceneCompanyExport", JsonUtil.toJson(sceneCompanyService.list(buildQW(req))), response);
    }
}
